package com.peoit.honeycomb.rest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.peoit.honeycomb.domain.exception.FileUploadException;
import com.peoit.honeycomb.util.CommonUtil;

/**
 * Created by Bing.Zeng on 2015/9/23.
 */
public class BaseResource {

	protected static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");

	/**
	 * 处理单个上传文件，存储到指定位置，返回文件路径
	 * 
	 * @param request
	 * @param file
	 * @return
	 */
	protected String storeUploadFile(HttpServletRequest request, MultipartFile file) {
		try {
			String newFileName = UUID.randomUUID().toString().replace("-", "");
			String folderPath = request.getRealPath("/upload");
			String extention = CommonUtil.getExtName(file.getOriginalFilename());
			String filePath = folderPath + File.separator + newFileName + extention;

			saveFile(file.getInputStream(), filePath);

			return "/upload/" + newFileName + extention;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new FileUploadException();
		}

	}

	/**
	 * 存储文件
	 * 
	 * @param stream
	 * @param fileFullPath
	 * @throws IOException
	 */
	private void saveFile(InputStream stream, String fileFullPath) throws IOException {
		FileOutputStream fs = null;
		try {
			fs = new FileOutputStream(fileFullPath);
			byte[] buffer = new byte[1024 * 1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = stream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
		} finally {
			fs.flush();
			fs.close();
			stream.close();
		}
	}
}
